package org.bot.plugin.web.drive;

import org.openqa.selenium.chrome.ChromeDriverService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeOptions;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.springframework.stereotype.Component;
import org.bot.api.config.ClientConfig;

import java.time.Duration;

@Component
public class LoadWeb {

    static Logger logger = LoggerFactory.getLogger(LoadWeb.class);

    public WebDriver load(ClientConfig clientConfig) {
        if (clientConfig.getDrive() != null) {
            System.setProperty(clientConfig.getDriveName(), clientConfig.getDrive());
        }
        WebDriver webDriver = null;
        logger.info("正在加载资源...");
        switch (ClientConfig.getBotConfig().getDriveName()) {
            case "webdriver.chrome.driver":
                ChromeOptions chromeOptions = new ChromeOptions();
                if (clientConfig.getBinary() != null) {
                    chromeOptions.setBinary(clientConfig.getBinary());
                }
                String[] arguments = clientConfig.getArguments();
                for (String argument : arguments) {
                    chromeOptions.addArguments(argument);
                }
                webDriver = new ChromeDriver(chromeOptions);
                break;
            case "webdriver.edge.driver":
                EdgeOptions edgeOptions = new EdgeOptions();
                if (clientConfig.getBinary() != null) {
                    edgeOptions.setBinary(clientConfig.getBinary());
                }
                webDriver = new EdgeDriver(edgeOptions);
                break;
            case "webdriver.gecko.driver":
                FirefoxOptions firefoxOptions = new FirefoxOptions();
                if (clientConfig.getBinary() != null) {
                    firefoxOptions.setBinary(clientConfig.getBinary());
                }
                webDriver = new FirefoxDriver(firefoxOptions);
                break;
        }

        if (clientConfig.getPageLoadTimeout() != null){
            logger.debug(String.format("设置页面最大超时时间为【%s】秒",clientConfig.getPageLoadTimeout()));
            webDriver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(clientConfig.getPageLoadTimeout() * 1000));
        }
        logger.info("加载资源完成...");
        return webDriver;
    }

}
